<template>
    <div>
        <div class="userManager">
            <div class="queryForm">
                <query-form
                    :form="searchLabel"
                    v-model="targetForm"
                    @searchHandler="search"
                    @cancelHandler="resetSearch"
                ></query-form>
            </div>
            <div class="baseTable">
                <div class="action">
                    <el-button type="primary" @click="roleAdd" v-has="'role-create'">
                        新增
                    </el-button>
                </div>
                <el-table ref="listRef" :data="roleList" style="width: 100%" row-key="_id">
                    <el-table-column
                        v-for="ele in columns"
                        :key="ele.prop"
                        :prop="ele.prop"
                        :label="ele.label"
                        :formatter="ele.formatter"
                        :width="ele.width"
                    />
                    <el-table-column label="操作" min-width="120">
                        <template #default="scope">
                            <el-button @click="permissionEdit(scope.row)" v-has="'role-setting'">
                                权限编辑
                            </el-button>
                            <el-button
                                type="primary"
                                @click="roleEdit(scope.row)"
                                :icon="Edit"
                                v-has="'role-edit'"
                            ></el-button>
                            <el-button
                                type="danger"
                                @click="roleDelete(scope.row)"
                                :icon="Delete"
                                v-has="'role-delete'"
                            />
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 角色编辑弹窗 -->
            <el-dialog v-model="showDialog" @close="close">
                <el-form :model="roleForm" ref="dialogForm" :rules="rules">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input v-model="roleForm.roleName" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="备注" prop="remark">
                        <el-input
                            v-model="roleForm.remark"
                            :rows="2"
                            type="textarea"
                            placeholder="在此输入备注"
                        />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancel">取消</el-button>
                        <el-button type="primary" @click="submit(dialogForm)">确定</el-button>
                    </span>
                </template>
            </el-dialog>
            <!-- 权限编辑弹窗 -->
            <el-dialog v-model="showPermission">
                <el-form>
                    <el-form-item label="权限设置">
                        <el-tree
                            :data="treeData"
                            show-checkbox
                            node-key="id"
                            :default-expanded-keys="rolePermission"
                            :default-checked-keys="rolePermission"
                            :props="treeProps"
                            ref="tree"
                        />
                    </el-form-item>
                </el-form>

                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="cancelPer">取消</el-button>
                        <el-button type="primary" @click="submitPer(tree)">确定</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>

<script setup>
import { Delete, Edit } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';
import { list } from 'postcss';
import { computed, nextTick, reactive, ref, toRaw } from 'vue';
import { useStore } from 'vuex';
import api from '../api';
import utils from '../utils';
import storage from '../utils/storage';
const treeProps = reactive({
    children: 'children',
    label: 'label',
});
/*节点、表单、请求体*/
const roleList = ref([]);
const columns = reactive([
    {
        label: '角色名称',
        prop: 'roleName',
    },
    {
        label: '备注',
        prop: 'remark',
    },
    {
        label: '权限列表',
        prop: 'permissionList',
        formatter: (row, column, value) => {
            let names = [];
            let { halfCheckedKeys } = value;
            halfCheckedKeys.map(key => {
                let name = actionMap[key];
                if (key && name) {
                    names.push(name);
                }
            });
            return names.join(',');
        },
        width: 210,
    },
    {
        label: '更新时间',
        prop: 'updateTime',
        formatter: (row, column, value) => {
            return utils.formateDate(new Date(value));
        },
        width: 210,
    },
    {
        label: '创建时间',
        prop: 'createTime',
        formatter: (row, column, value) => {
            return utils.formateDate(new Date(value));
        },
        width: 210,
    },
]);
const rules = reactive({
    roleName: [
        {
            required: true,
            message: '请输入角色名称',
            trigger: 'blur',
        },
    ],
});
const rolePermission = ref([]);
const permissionEditData = {};

const dialogForm = ref(null);
const targetRef = ref(null);
const tree = ref(null);
let targetForm = reactive([]);
let roleForm = reactive({});
const searchLabel = [
    {
        type: 'input',
        label: '角色名称',
        prop: 'targetName',
        placeholder: '请输入角色名称',
    },
];
/*普通变量*/
const store = useStore();
let showDialog = ref(false);
let action = ref('add');
let showPermission = ref(false);
// 映射表
let actionMap = reactive({});
const getActionMap = () => {
    let list = storage.getItem('menuList');
    let map = {};
    const deep = arr => {
        while (arr.length) {
            let item = arr.pop();
            if (item.children && item.action) {
                // 二级菜单
                map[item._id] = item.menuName;
            } else if (item.children) {
                // 一级菜单
                deep(item.children);
            }
        }
    };
    deep(JSON.parse(JSON.stringify(list))); //需要进行深拷贝，因为浅拷贝会影响list。
    // console.log(map);
    actionMap = map;
};
/*树状*/
let treeData = [];
/*用于请求的函数*/
const getRoleList = async data => {
    let { list } = await api.getRoleList(data);
    roleList.value = list;
};
const operateRole = async data => {
    data['action'] = action.value;
    await api.roleOperate(data);
};
const getPremissionList = async () => {
    let list = await api.getMenuList();
    list.forEach(ele => {
        treeData.push(permissionTree(ele));
    });
};
const permissionOperate = async data => {
    let res = await api.permissionEdit(data);
};
/*点击事件函数*/
//搜索板块
const search = () => {
    getRoleList({
        roleName: targetForm.targetName,
    });
};
const resetSearch = () => {
    getRoleList();
};
// 增删改
const roleAdd = () => {
    action.value = 'create';
    showDialog.value = !showDialog.value;
};
const roleEdit = row => {
    action.value = 'edit';
    showDialog.value = !showDialog.value;
    nextTick(() => {
        Object.assign(roleForm, row);
    });
};
const roleDelete = row => {
    action.value = 'delete';
    let data = {
        _id: row._id,
    };
    operateRole(data);
    getRoleList();
};
const permissionEdit = row => {
    permissionEditData['_id'] = row._id;
    showPermission.value = !showPermission.value;
    rolePermission.value = row.permissionList.checkedKeys;
};
//框
const cancel = () => {
    dialogForm.value.resetFields();
    showDialog.value = !showDialog.value;
};
const close = () => {
    dialogForm.value.resetFields();
};
const submit = dialogForm => {
    dialogForm.validate(vaild => {
        if (vaild) {
            try {
                let form = toRaw(roleForm);
                delete form['__v'];
                delete form['createTime'];
                delete form['permissionList'];
                delete form['updateTime'];
                operateRole(form);
                getRoleList();
                showDialog.value = !showDialog.value;
                dialogForm.resetFields();
                ElMessage({
                    message: '提交成功',
                    type: 'success',
                });
            } catch (error) {
                ElMessage.error('提交失败');
                console.log(error);
            }
        }
    });
};
const cancelPer = () => {
    showPermission.value = !showPermission.value;
};
const submitPer = tree => {
    permissionEditData['permissionList'] = {
        checkedKeys: [], //选中的子菜单
        halfCheckedKeys: [], //半选中的父菜单
    };
    let tempAll = tree.getCheckedNodes(true, false);
    let tempHalf = tree.getCheckedNodes(false, true);
    tempAll.forEach(ele => {
        permissionEditData.permissionList.checkedKeys.push(ele.id);
    });
    tempHalf.forEach(ele => {
        permissionEditData.permissionList.halfCheckedKeys.push(ele.id);
    });
    permissionOperate(permissionEditData);
    getRoleList();
    showPermission.value = !showPermission.value;
};
/*交互事件函数*/
/*树状函数*/
const permissionTree = node => {
    if (!node['children']) {
        return {
            id: node._id,
            label: node.menuName,
            disabled: node.menuState == 2 ? true : false,
        };
    } else {
        let childrenList = [];
        node.children.forEach(ele => {
            childrenList.push(permissionTree(ele));
        });
        return {
            id: node._id,
            label: node.menuName,
            disabled: node.menuState == 2 ? true : false,
            children: childrenList,
        };
    }
};

/*调用*/
getPremissionList();
getRoleList();
getActionMap();
</script>

<style lang="scss" scoped>
.queryForm {
    width: 100%;
    height: 65px;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    display: flex;
    align-items: center;
    padding-top: 20px;
    padding-left: 40px;
}
.baseTable {
    margin-top: 20px;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    .action {
        width: 100%;
        height: 55px;
        display: flex;
        align-items: center;
        border-bottom: 1px solid #f1f1f1;
        button {
            margin-left: 20px;
            font-weight: bold;
        }
    }
}
</style>
